package com.yunpuvip.sachet.modular.page;

import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.yunpuvip.sachet.modular.constant.enumconstant.Order;
import com.yunpuvip.sachet.modular.factory.Order;
import com.yunpuvip.sachet.modular.factory.Order;
import com.yunpuvip.sachet.modular.util.kit.HttpKit;

import javax.servlet.http.HttpServletRequest;

/**
 * rest 分页
 *
 * @author hyf
 * @date 2019-03-07
 **/
public class RestPageFactory<T> {

    public Page<T> defaultPage() {
        HttpServletRequest request = HttpKit.getRequest();

        //一页显示数量
        String spageSize = request.getParameter("pageSize");
        int pageSize = 10;
        if (spageSize != null) {

            pageSize = Integer.valueOf(spageSize);
            //限制一下每页显示数量，怕出问题
            if (pageSize > 50) {
                pageSize = 50;
            }
        }

        //当前页
        String spageNum = request.getParameter("pageNum");
        int pageNum = 1;
        if (spageNum != null) {
            pageNum = Integer.valueOf(spageNum);
        }
        //排序字段名称
        String sort = request.getParameter("sort");
        //asc或desc(升序或降序)
        String order = request.getParameter("order");
        if (ToolUtil.isEmpty(sort)) {
            Page<T> page = new Page<>(pageNum, pageSize);
            return page;
        } else {
            Page<T> page = new Page<>(pageNum, pageSize);
            if (Order.ASC.getDes().equals(order)) {
                page.setAsc(sort);
            } else {
                page.setDesc(sort);
            }
            return page;
        }
    }

    /**
     * redis 的默认分页
     *
     * @param
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<T>
     * @author hyf
     * @date 2019/5/8
     */
    public RedisPage<T> redisDefaultPage() {
        HttpServletRequest request = HttpKit.getRequest();
        //一页显示数量
        String spageSize = request.getParameter("pageSize");
        int pageSize = 10;
        if (spageSize != null) {
            pageSize = Integer.valueOf(spageSize);
            //限制一下每页显示数量，怕出问题
            if (pageSize > 50) {
                pageSize = 50;
            }
            if (pageSize <= 0) {
                pageSize = 10;
            }
        }
        //当前页
        String spageNum = request.getParameter("pageNum");
        int pageNum = 1;
        if (spageNum != null) {
            pageNum = Integer.valueOf(spageNum) > 0 ? Integer.valueOf(spageNum) : pageNum;
        }
        return new RedisPage<>(pageNum, pageSize);
    }
}
